﻿using System;
using System.Linq;

namespace SmartAssembly
{
    internal static class ReportUtils
    {
        internal static string GetAssemblyNameOrNull(string typeName)
        {
            if (!typeName.StartsWith("["))
            {
                return null;
            }
            int index = typeName.IndexOf(']');
            if (index < 0)
            {
                return null;
            }
            return typeName.Substring(1, index - 1);
        }

        internal static string GetHumanTypeName(string typeName)
        {
            string lastIdentifier = typeName.Split('.', ']').LastOrDefault();
            if (!String.IsNullOrEmpty(lastIdentifier))
            {
                if (lastIdentifier.All(c => !Char.IsWhiteSpace(c)))
                {
                    return lastIdentifier;
                }
            }

            return typeName;
        }

        internal static string GetHumanMethodName(string methodName)
        {
            int parenthesisIndex = methodName.LastIndexOf('(');
            if (parenthesisIndex > 0)
            {
                string methodNameNoArgs = methodName.Substring(0, parenthesisIndex);
                int spaceIndex = methodNameNoArgs.LastIndexOf(' ');
                if (spaceIndex > 0)
                {
                    // IsDefinitelyIdentifier() is overly restrictive so don't check here
                    string humanMethodName = methodNameNoArgs.Substring(spaceIndex + 1);
                    return humanMethodName;
                }
            }

            return methodName;
        }
    }
}
